using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum EAudioType
{
    CLICK,
    GOAL,
    WIN,
    LOSE

}

public class AudioManager : MonoBehaviour
{
    [SerializeField] private AudioClip clickClip;
    [SerializeField] private AudioClip goalClip;
    [SerializeField] private AudioClip winClip;

    public GameObject audioPrefab;
    public int poolSize = 10;

    private Queue<AudioSource> audioPool;

    void Awake()
    {
        GameManager.Instance().audioManager = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        audioPool = new Queue<AudioSource>();

        for (int i = 0; i < poolSize; i++)
        {
            GameObject audioGameObject = Instantiate(audioPrefab);
            audioGameObject.transform.SetParent(transform);
            AudioSource audioSource = audioGameObject.GetComponent<AudioSource>();
            audioPool.Enqueue(audioSource);
        }
    }

    /// <summary>
    /// 播放音频文件
    /// </summary>
    /// <param name="clip"></param>
    private void PlaySoundEffect(AudioClip clip)
    {
        if (audioPool.Count > 0)
        {
            AudioSource audioSource = audioPool.Dequeue();
            // audioSource.Play();
            audioSource.PlayOneShot(clip, 3f);
            StartCoroutine(ReturnToPool(audioSource, clip.length));
        }
    }

    /// <summary>
    /// 根据音频类型播放音频
    /// </summary>
    /// <param name="audioType"></param>
    public void PlayAudio(EAudioType audioType)
    {
        switch (audioType)
        {
            case EAudioType.CLICK:
                PlaySoundEffect(clickClip);
                break;
            case EAudioType.GOAL:
                PlaySoundEffect(goalClip);
                break;
            case EAudioType.WIN:
                PlaySoundEffect(winClip);
                break;
            case EAudioType.LOSE:
                break;
        }
    }

    private IEnumerator ReturnToPool(AudioSource audioSource, float delay)
    {
        yield return new WaitForSeconds(delay);
        audioPool.Enqueue(audioSource);
    }

    // Update is called once per frame
    void Update()
    {

    }
}
